<?php

namespace App\Console\Commands\User;

use Illuminate\Console\Command;
use App\Models\User;

class SetUserCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'user:set';

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user:set
        {username : The username}
        {password : The password}
        {role? : The role of the user, old as default}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Set an exist user';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        // 获取参数
        $username = $this->argument('username');
        $password = $this->argument('password');
        $role = $this->argument('role');

        // 密码加密
        $password = password_hash($password, PASSWORD_DEFAULT);

        // 检查用户存在性
        $user = User::where('username', $username)->first();
        if ($user) {
            // 默认使用原有的用户组
            $role = $role ? $role : $user->role;
            $user->update([
                'username' => $username,
                'password' => $password,
                'role'     => $role,
            ]);
            $this->info('User set successfully!');
        } else {
            $this->error('User not found!');
        }
    }
}
